<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色管理" name="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="dialogVisible=true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="List">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="id" label="操作">
                <template #default="{row}">
                  <el-button
                    size="small"
                    type="success"
                    @click="assign(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRole(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delBtn(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page"
                :page-sizes="[1,2,3,4,5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
            <!-- 分页 -->

          </el-tab-pane>
          <el-tab-pane label="公司信息" name="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input :value="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input :value="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input :value="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input :value="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        :title="addOrEdit"
        :visible.sync="dialogVisible"
        width="50%"
        @close="btnCancel"
      >
        <el-form ref="form" :model="roleForm" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="btnCancel">取 消</el-button>
          <el-button
            type="primary"
            @click="btnOk"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
        <el-tree
          ref="tree"
          v-loading="premLoading"
          :data="permissionList"
          node-key="id"
          :props="{ label:'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          highlight-current
        />
        <template #footer>
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button
            type="primary"
            @click="clickAssignSubmit"
          >确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    return {
      activeName: '角色管理',
      List: [],
      page: 1,
      pagesize: 3,
      total: 0,
      dialogVisible: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名字不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      loading: false,
      // 公司信息对象
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      roleId: null,
      permissionList: [],
      premLoading: false
    }
  },
  computed: {
    addOrEdit() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyById()
  },
  methods: {
    // 分配权限按钮
    closeAssignDialog() {
      this.roleId = null
      this.permissionList = []
      this.$refs.tree.setCheckedKeys([])
      this.showAssignDialog = false
    },
    async assign(id) {
      this.premLoading = true
      this.roleId = id
      this.showAssignDialog = true
      this.permissionList = tranListToTreeData(await this.apis.permission.getPermissionList(), '0')
      const { permIds } = await this.apis.setting.getRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
      this.premLoading = false
    },
    async clickAssignSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await this.apis.setting.assignPerm(this.roleId, permIds)
      this.$message.success('分配角色权限成功')
      this.closeAssignDialog()
    },
    // 分配权限按钮

    btnOk() {
      this.$refs.form.validate(async isOk => {
        if (!isOk) return // 校验通过
        // 判断是编辑还是新增
        // 调接口
        if (this.roleForm.id) {
          await this.apis.setting.updateRole(this.roleForm)
          this.$message.success('编辑角色成功')
        } else {
          await this.apis.setting.addRole(this.roleForm)
          this.$message.success('新增角色成功')
        }
        this.getRoleList()
        // 关闭弹层，清空数据，放在btnCancel里做，这里调方法
        this.btnCancel()
      })
    },
    btnCancel() {
      // 清空表单数据，表单id等属性也清空
      this.roleForm = {
        name: '',
        description: ''
      }
      // 同时清空表单数据和校验规则
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    async editRole(id) {
      this.roleForm = await this.apis.setting.getRoleDetail(id)
      this.dialogVisible = true
    },
    async delBtn(id) {
      try {
        await this.$confirm('确定要删除该角色吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await this.apis.setting.deleteRole(id)
        if (this.page !== 1 && this.List.length === 1) {
          this.page--
        }
        this.getRoleList()
        this.$message.success('删除角色成功')
      } catch (err) {
        console.log(err)
      }
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    async getRoleList() {
      this.loading = true
      const res = await this.apis.setting.getRoleList({ page: this.page, pagesize: this.pagesize })
      // console.log(res)
      this.List = res.rows
      this.total = res.total
      this.loading = false
    },
    handleSizeChange(val) {
      // 改变pagesize时触发
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // 改变page时触发
      // console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },
    async getCompanyById() {
      const res = await this.apis.employees.getCompanyById(this.$store.state.user.userInfo.companyId)
      // console.log(res)
      this.companyForm = res
    }
  }
}
</script>

<style>

</style>
